﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
using System.Data.Common;

public partial class Components_Permission_FunctionList : System.Web.UI.Page
{
    DatabaseHelper DB = new DatabaseHelper();
    DataTable dt = new DataTable();
    int ParentID = 20; //ID trong CSDL, bảng Function
    static int FormState = -1; //trạng thái form ban đầu
    string ID = "";
    string i_UserID;
    int idedit;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            i_UserID = Session["UserName"].ToString();//huy add
            if (Session["FunctionID"] == null)
                FormState = 0;
            else
                FormState = (int)Session["Function"];

            if (!IsPostBack)
            {
                txtOderal.Text = "1";
                SetupForm();
                switch (FormState)
                {
                    case 0:
                        {
                            break;
                        }
                    default:
                        {
                            ID = Session["FunctionID"].ToString();
                            LoadDatatoForm();
                            LoadListFunction_ParentID();
                            break;
                        }
                }
            }
        }
        catch (Exception ex)
        {
            switch (FormState)
            {
                case 0:
                    {

                        string url = "~/Default.aspx?ID=48";
                        Response.Redirect(url);
                        Session["ErrorMessage"] = ex.Message;

                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
        Session.Remove("FunctionID");

    }
    protected void SetupForm()
    {
        //Load dữ liệu cho các control khi vừa load form
        Utils.LoadDataToCombo(cboFunctionParent, "Function_cbo_Parent");
        cboFunctionParent.SelectedIndex = 0;
        Utils.LoadCodeDetail(cboFunctionType, "FunctionType", 0);
        cboFunctionType.SelectedIndex = 0;
        cboFunctionLevel.SelectedIndex = 0;
        txtOderal.Text = "1";
        SetEnable();
        LoadListFunction_ParentID();
        // load lưới khi chưa có thông tin 
        //DataTable dt = new DataTable();
        //grvData.DataSource = dt;
        //grvData.DataBind();
    }

    protected void ClearForm()
    {
        cboFunctionLevel.SelectedIndex = 0;
        cboFunctionParent.SelectedIndex = 0;
        cboFunctionType.SelectedIndex = 0;
        txtFunctionName.Text = "";
        txtOderal.Text = "1";
        txtWebScreen.Text = "";
        txtFunctionCode.Text = "";
        radPublicFunction.Checked = true;
        FormState = 0;
    }

    protected void SetEnable()
    {
        switch (FormState)
        {
            case 0://Thêm mới
                {
                    btnDelete.Enabled = false;
                    //btnUpdate.Enabled = false;
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;
                    btnDelete.CssClass = "Enable";
                    //  btnUpdate.CssClass = "Enable";
                    break;
                }
            case 1://Sửa/Xóa
                {
                    btnDelete.Enabled = true;
                    //  btnUpdate.Enabled = true;
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;
                    break;
                }
            default://Chỉ xem
                {
                    btnDelete.Visible = false;
                    // btnUpdate.Visible = false;
                    btnGotoList.Visible = false;
                    btnNew.Visible = false;
                    btnSave.Visible = false;
                    break;
                }
        }
    }

    protected void LoadDatatoForm()
    {
        DB.ClearParameter();

        DbParameter paramCMCode = DB.Parameter;
        paramCMCode.ParameterName = "ID";
        paramCMCode.DbType = DbType.String;
        paramCMCode.Value = ID;
        DB.AddParameter(paramCMCode);
        dt = DB.ExecuteDataTable("Function_Load", CommandType.StoredProcedure, ConnectionState.CloseOnExit);

        if (dt.Rows.Count == 1)
        {
            DataRow dr = dt.Rows[0];
            cboFunctionParent.SelectedValue = dr["ParentID"].ToString();
            cboFunctionLevel.Text = dr["FunctionLevel"].ToString();
            cboFunctionType.SelectedValue = dr["FunctionType"].ToString();
            txtFunctionCode.Text = dr["ID"].ToString();
            txtFunctionName.Text = dr["FunctionName"].ToString();
            txtOderal.Text = dr["Ordinal"].ToString();
            txtWebScreen.Text = dr["WebScreen"].ToString();
            string IsSysFunction = dr["IsSysFunction"].ToString();
            if (IsSysFunction == "True")
            {
                radSysFunction.Focus();
            }
            else
            {
                radPublicFunction.Focus();

            }
        }
    }

    protected void SaveData()
    {
        DB.ClearParameter();
        try
        {
            if (txtFunctionCode.Text == null || txtFunctionCode.Text == "")
                FormState = 0;
            else
                FormState = 1;
            if (txtFunctionName.Text == "")
            {
                txtFunctionName.Focus();
                lblResult.Text = "";
                lblSuccess.Text = "";
                lblResult.Text = "Tên chức năng không rỗng";
                return;
            }
            if (txtWebScreen.Text == "")
            {
                txtWebScreen.Focus();
                lblResult.Text = "";
                lblSuccess.Text = "";
                lblResult.Text = "Đường dẫn không rỗng ";
                return;
            }
            if (txtGroupID.Text == "")
            {
                txtGroupID.Focus();
                lblResult.Text = "";
                lblSuccess.Text = "";
                lblResult.Text = "Cấp chức năng không được rỗng ";
            }
            //bỏ những ký tự đặc biệt, chống SQL Injection
            txtFunctionName.Text = Utils.KillChars(txtFunctionName.Text);
            txtOderal.Text = Utils.KillChars(txtOderal.Text);
            cboFunctionType.Text = Utils.KillChars(cboFunctionType.Text);
            cboFunctionParent.Text = Utils.KillChars(cboFunctionParent.Text);
            cboFunctionLevel.Text = Utils.KillChars(cboFunctionLevel.Text);
            txtWebScreen.Text = Utils.KillChars(txtWebScreen.Text);
            bool FunctionIsSysFun = false;
            if (radPublicFunction.Checked == true)
                FunctionIsSysFun = false;
            else
                FunctionIsSysFun = true;
            //Add param cho store
            DbParameter paramParentCode = DB.Parameter;
            paramParentCode.ParameterName = "ParentID";
            paramParentCode.DbType = DbType.String;
            paramParentCode.Value = cboFunctionParent.SelectedValue;
            DB.AddParameter(paramParentCode);

            DbParameter paramFunctionName = DB.Parameter;
            paramFunctionName.ParameterName = "FunctionName";
            paramFunctionName.DbType = DbType.String;
            paramFunctionName.Value = txtFunctionName.Text;
            DB.AddParameter(paramFunctionName);

            DbParameter paramFunctionLevel = DB.Parameter;
            paramFunctionLevel.ParameterName = "FunctionLevel";
            paramFunctionLevel.DbType = DbType.Int32;
            paramFunctionLevel.Value = cboFunctionLevel.Text;
            DB.AddParameter(paramFunctionLevel);

            DbParameter paramFunctionType = DB.Parameter;
            paramFunctionType.ParameterName = "FunctionType ";
            paramFunctionType.DbType = DbType.String;
            paramFunctionType.Value = cboFunctionType.SelectedValue;
            DB.AddParameter(paramFunctionType);

            DbParameter paramFunctionOrdinal = DB.Parameter;
            paramFunctionOrdinal.ParameterName = "Ordinal";
            paramFunctionOrdinal.DbType = DbType.Int32;
            paramFunctionOrdinal.Value = txtOderal.Text;
            DB.AddParameter(paramFunctionOrdinal);

            DbParameter paramFunctionIsSysFun = DB.Parameter;
            paramFunctionIsSysFun.ParameterName = "IsSysFunction";
            paramFunctionIsSysFun.DbType = DbType.Byte;
            paramFunctionIsSysFun.Value = FunctionIsSysFun;
            DB.AddParameter(paramFunctionIsSysFun);

            DbParameter paramWebScreen = DB.Parameter;
            paramWebScreen.ParameterName = "WebScreen";
            paramWebScreen.DbType = DbType.String;
            paramWebScreen.Value = txtWebScreen.Text;
            DB.AddParameter(paramWebScreen);

            DbParameter paramFunctionStatus = DB.Parameter;
            paramFunctionStatus.ParameterName = "Status";
            paramFunctionStatus.DbType = DbType.String;
            paramFunctionStatus.Value = 'A';
            DB.AddParameter(paramFunctionStatus);

            DbParameter paramGroupID = DB.Parameter;
            paramGroupID.ParameterName = "GroupID";
            paramGroupID.DbType = DbType.Int32;
            paramGroupID.Value = txtGroupID.Text;
            DB.AddParameter(paramGroupID);

            DbParameter paramGroupOrdial = DB.Parameter;
            paramGroupOrdial.ParameterName = "GroupOrdinal";
            paramGroupOrdial.DbType = DbType.Byte;
            paramGroupOrdial.Value = 0;
            DB.AddParameter(paramGroupOrdial);

            DbParameter paramCreateBy = DB.Parameter;
            paramCreateBy.ParameterName = "ByUser";
            paramCreateBy.DbType = DbType.String;
            paramCreateBy.Value = i_UserID;
            DB.AddParameter(paramCreateBy);

            if (FormState == 0)
            {
                dt = DB.ExecuteDataTable("Function_Insert", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                lblResult.Text = "";
                lblSuccess.Text = "";
                lblSuccess.Text = "Thêm mới thành công";
                btnDelete.Enabled = true;
                btnDelete.CssClass = "button";
                Session["FunctionIDA"] = DB.ExecuteScalar("Function_ID", CommandType.StoredProcedure, ConnectionState.CloseOnExit).ToString();
                txtFunctionCode.Text = Session["FunctionIDA"].ToString();
                FormState = 1;
            }
            else if (FormState == 1)
            {
                //add thuộc tính ID để cập nhật
                ID = txtFunctionCode.Text;
                ID = Utils.KillChars(ID);

                DbParameter paramID = DB.Parameter;
                paramID.ParameterName = "ID";
                paramID.DbType = DbType.Int32;
                paramID.Value = ID;
                DB.AddParameter(paramID);
                dt = DB.ExecuteDataTable("Function_Update", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                lblResult.Text = "";
                lblSuccess.Text = "";
                lblSuccess.Text = "Cập nhật thành công";
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Text = "";
            lblResult.Text = "";
            lblResult.Text = "Thông báo lỗi: Lưu không thành công. Mã lỗi: CodeDetail - " + ex.Message;
        }

    }

    protected void DeleteData()
    {
        DB.ClearParameter();
        if (FormState == 0)
        {
            object i = DB.ExecuteScalar("Function_ID", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            ID = i.ToString();
        }
        else if (FormState == 1)
        {
            ID = Session["FunctionID"].ToString();
            ID = Utils.KillChars(ID);
        }
        DbParameter paramID = DB.Parameter;
        paramID.ParameterName = "ID";
        paramID.DbType = DbType.Int32;
        paramID.Value = int.Parse(Session["FunctionID"].ToString());
        DB.AddParameter(paramID);
        try
        {
            dt = DB.ExecuteDataTable("DeleteFunction", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            lblResult.Text = "";
            lblSuccess.Text = "";
            lblSuccess.Text = "Xóa thành công";
        }
        catch (Exception ex)
        {
            lblResult.Text = "";
            lblSuccess.Text = "";
            lblResult.Text = "Thông báo lỗi: Xóa không thành công. Mã lỗi: CodeDetail - " + ex.Message;
        }
    }

    protected Boolean CheckAllBeforeSave()
    {
        Boolean flag = true;
        if (txtFunctionName.Text == "")
        {
            //lblResult.Text = "[Tên danh mục] không được rỗng";
            flag = false;
        }
        return flag;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string funtion_id = txtFunctionCode.Text;
        if (funtion_id != "")
        {
            try
            {
                if (idedit != null)
                {
                    //FormState =1;
                    ID = txtFunctionCode.Text;
                    ID = Utils.KillChars(ID);

                    DbParameter paramID = DB.Parameter;
                    paramID.ParameterName = "ID";
                    paramID.DbType = DbType.Int32;
                    paramID.Value = ID;
                    DB.AddParameter(paramID);

                    txtFunctionName.Text = Utils.KillChars(txtFunctionName.Text);
                    txtOderal.Text = Utils.KillChars(txtOderal.Text);
                    cboFunctionType.Text = Utils.KillChars(cboFunctionType.Text);
                    cboFunctionParent.Text = Utils.KillChars(cboFunctionParent.Text);
                    cboFunctionLevel.Text = Utils.KillChars(cboFunctionLevel.Text);
                    txtWebScreen.Text = Utils.KillChars(txtWebScreen.Text);
                    bool FunctionIsSysFun = false;
                    if (radPublicFunction.Checked == true)
                        FunctionIsSysFun = false;
                    else
                        FunctionIsSysFun = true;
                    //Add param cho store
                    DbParameter paramParentCode = DB.Parameter;
                    paramParentCode.ParameterName = "ParentID";
                    paramParentCode.DbType = DbType.String;
                    paramParentCode.Value = cboFunctionParent.SelectedValue;
                    DB.AddParameter(paramParentCode);

                    DbParameter paramFunctionName = DB.Parameter;
                    paramFunctionName.ParameterName = "FunctionName";
                    paramFunctionName.DbType = DbType.String;
                    paramFunctionName.Value = txtFunctionName.Text;
                    DB.AddParameter(paramFunctionName);

                    DbParameter paramFunctionLevel = DB.Parameter;
                    paramFunctionLevel.ParameterName = "FunctionLevel";
                    paramFunctionLevel.DbType = DbType.Int32;
                    paramFunctionLevel.Value = cboFunctionLevel.Text;
                    DB.AddParameter(paramFunctionLevel);

                    DbParameter paramFunctionType = DB.Parameter;
                    paramFunctionType.ParameterName = "FunctionType ";
                    paramFunctionType.DbType = DbType.String;
                    paramFunctionType.Value = cboFunctionType.SelectedValue;
                    DB.AddParameter(paramFunctionType);

                    DbParameter paramFunctionOrdinal = DB.Parameter;
                    paramFunctionOrdinal.ParameterName = "Ordinal";
                    paramFunctionOrdinal.DbType = DbType.Int32;
                    paramFunctionOrdinal.Value = txtOderal.Text;
                    DB.AddParameter(paramFunctionOrdinal);

                    DbParameter paramFunctionIsSysFun = DB.Parameter;
                    paramFunctionIsSysFun.ParameterName = "IsSysFunction";
                    paramFunctionIsSysFun.DbType = DbType.Byte;
                    paramFunctionIsSysFun.Value = FunctionIsSysFun;
                    DB.AddParameter(paramFunctionIsSysFun);

                    DbParameter paramWebScreen = DB.Parameter;
                    paramWebScreen.ParameterName = "WebScreen";
                    paramWebScreen.DbType = DbType.String;
                    paramWebScreen.Value = txtWebScreen.Text;
                    DB.AddParameter(paramWebScreen);

                    DbParameter paramFunctionStatus = DB.Parameter;
                    paramFunctionStatus.ParameterName = "Status";
                    paramFunctionStatus.DbType = DbType.String;
                    paramFunctionStatus.Value = 'A';
                    DB.AddParameter(paramFunctionStatus);

                    DbParameter paramGroupID = DB.Parameter;
                    paramGroupID.ParameterName = "GroupID";
                    paramGroupID.DbType = DbType.Int32;
                    paramGroupID.Value = txtGroupID.Text;
                    DB.AddParameter(paramGroupID);

                    DbParameter paramGroupOrdial = DB.Parameter;
                    paramGroupOrdial.ParameterName = "GroupOrdinal";
                    paramGroupOrdial.DbType = DbType.Byte;
                    paramGroupOrdial.Value = 0;
                    DB.AddParameter(paramGroupOrdial);

                    DbParameter paramCreateBy = DB.Parameter;
                    paramCreateBy.ParameterName = "ByUser";
                    paramCreateBy.DbType = DbType.String;
                    paramCreateBy.Value = i_UserID;
                    DB.AddParameter(paramCreateBy);

                    dt = DB.ExecuteDataTable("Function_Update", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                    lblResult.Text = "";
                    lblSuccess.Text = "";
                    lblSuccess.Text = "Cập nhật thành công";
                    btnSave.Enabled = true;
                    btnSave.CssClass = "button";
                }
                FormState = 1;
                LoadListFunction_ParentID();
            }
            catch (Exception ex)
            {
                string url = "~/Default.aspx?ID=48";
                Response.Redirect(url);
                Session["ErrorMessage"] = ex.Message;
            }

        }
        else
        {
            try
            {

                SaveData();
                FormState = 1;
                LoadListFunction_ParentID();
                btnDelete.Focus();
            }
            catch (Exception ex)
            {
                string url = "~/Default.aspx?ID=48";
                Response.Redirect(url);
                Session["ErrorMessage"] = ex.Message;
            }
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        DeleteData();
        ClearForm();
        SetEnable();
        LoadListFunction_ParentID();
        btnNew.Focus();
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        ClearForm();
        SetEnable();
        btnSave.CssClass = "button";
        btnSave.Enabled = true;
        btnGotoList.Focus();

    }
    protected void btnGotoList_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx?ID=" + ParentID);
    }
    protected void cboFunctionType_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        cboFunctionParent.Focus();
    }
    private void LoadListFunction_ParentID()
    {
        DbParameter paramParentID = DB.Parameter;
        paramParentID.ParameterName = "ParentID";
        paramParentID.DbType = DbType.Int32;
        paramParentID.Value = cboFunctionParent.SelectedValue;
        DB.AddParameter(paramParentID);

        dt = DB.ExecuteDataTable("Function_Search_ParentID", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
        this.grvData.DataSource = dt;
        this.grvData.DataBind();
        this.grvData.Visible = true;
    }
    protected void cboFunctionParent_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        FormState = 0;
        int i_test = int.Parse(cboFunctionParent.SelectedValue.ToString());
        LoadListFunction_ParentID();
        txtFunctionName.Focus();
    }

    protected void grvData_ItemCommand(object sender, GridCommandEventArgs e)
    {
        try
        {
            string commandName = e.CommandName;


            if (commandName == "EditDelItem")
            {
                int iRow = e.Item.ItemIndex;
                Session["FunctionID"] = grvData.Items[iRow]["ID"].Text.Replace("&nbsp;", "");

                DbParameter paramID = DB.Parameter;
                paramID.ParameterName = "ID";
                paramID.DbType = DbType.Int32;
                paramID.Value = int.Parse(Session["FunctionID"].ToString());
                DB.AddParameter(paramID);
                try
                {
                    dt = DB.ExecuteDataTable("DeleteFunction", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                    lblResult.Text = "";
                    lblSuccess.Text = "";
                    lblSuccess.Text = "Xóa thành công";
                }
                catch (Exception ex)
                {
                    lblResult.Text = "";
                    lblSuccess.Text = "";
                    lblResult.Text = "Thông báo lỗi: Xóa không thành công. Mã lỗi: CodeDetail - " + ex.Message;
                }
                LoadListFunction_ParentID();
                FormState = 1;
                cboFunctionParent.Text = grvData.Items[iRow]["FunctionName"].Text.Replace("nbsp;", "");
                cboFunctionLevel.SelectedValue = grvData.Items[iRow]["FunctionLevel"].Text.Replace("nbsp;", "");
                txtGroupID.Text = grvData.Items[iRow]["GroupID"].Text.Replace("nbsp;", "");
                txtWebScreen.Text = grvData.Items[iRow]["WebScreen"].Text.Replace("nbsp;", "");
                txtOderal.Text = grvData.Items[iRow]["Ordinal"].Text.Replace("nbsp;", "");
                cboFunctionType.Text = grvData.Items[iRow]["FunctionType"].Text.Replace("nbsp;", "");
                cboFunctionParent.Text = grvData.Items[iRow]["ParentID"].Text.Replace("nbsp;", "");
                // Session[DetailName] = 1; //0: tạo mới; 1: Sửa/Xóa; 2: Chỉ xem
                //  string s = grvData.Items[iRow]["ID"].Text.Replace("nbsp;", "");
                //  Response.Redirect("~/Default.aspx?ID=" + DetailID);
            }
            if (commandName == "EditItem")
            {
                FormState = 1;
                int iRow = e.Item.ItemIndex;
                Session["FunctionID"] = grvData.Items[iRow]["ID"].Text.Replace("&nbsp;", "");
                idedit = int.Parse(grvData.Items[iRow]["ID"].Text);
                txtFunctionName.Text = grvData.Items[iRow]["FunctionName"].Text.Replace("nbsp;", "");
                cboFunctionLevel.SelectedValue = grvData.Items[iRow]["FunctionLevel"].Text.Replace("nbsp;", "");
                txtGroupID.Text = grvData.Items[iRow]["GroupID"].Text.Replace("nbsp;", "");
                txtWebScreen.Text = grvData.Items[iRow]["WebScreen"].Text.Replace("nbsp;", "");
                txtOderal.Text = grvData.Items[iRow]["Ordinal"].Text.Replace("nbsp;", "");
                txtFunctionCode.Text = grvData.Items[iRow]["ID"].Text.Replace("nbsp;", "");
                cboFunctionType.SelectedValue = grvData.Items[iRow]["FunctionType"].Text.Replace("nbsp;", "");
                cboFunctionParent.Text = grvData.Items[iRow]["ParentID"].Text.Replace("nbsp;", "");

                GridEditableItem item = e.Item as GridEditableItem;
                CheckBox chkIsSysFunction = item.FindControl("chkIsSysFunction") as CheckBox;
                if (chkIsSysFunction.Checked == true)
                {

                    radSysFunction.Checked = true;
                    radPublicFunction.Checked = false;
                }
                else
                {

                    radPublicFunction.Checked = true;
                    radSysFunction.Checked = false;
                }
                // btnUpdate.Enabled = false;
                //btnUpdate.CssClass =  "Enable";
                btnDelete.Enabled = true;
                btnDelete.CssClass = "button";
                btnSave.Enabled = true;
                btnSave.CssClass = "button";


            }
        }
        catch (Exception ex)
        {
            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;
        }
    }
    
    protected void grvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
    }
    protected void txtFunctionName_TextChanged(object sender, EventArgs e)
    {
        cboFunctionLevel.Focus();
    }
    protected void cboFunctionLevel_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        txtGroupID.Focus();
    }
    protected void txtGroupID_TextChanged(object sender, EventArgs e)
    {
        txtOderal.Focus();
    }
    protected void txtOderal_TextChanged(object sender, EventArgs e)
    {
        txtWebScreen.Focus();
    }
    protected void txtWebScreen_TextChanged(object sender, EventArgs e)
    {
        radSysFunction.Focus();
    }
    protected void radSysFunction_CheckedChanged(object sender, EventArgs e)
    {
        radPublicFunction.Focus();
    }
}